#!/usr/local/bin/python2.5

import urllib, sys
from xml.dom import minidom
from pottononline.map.models import *

verbose = True

URL="http://rss.nestoria.co.uk/potton/property/buy"

fp = urllib.urlopen(URL)
rss = fp.read()
fp.close()
dom = minidom.parseString(rss)


try:
  housetype = MarkerType.objects.get(name="House for sale")
except:
  print "Error:  You probably have a new database, and haven't created the Marker Type of 'House for sale'."
  sys.exit(-1)

# delete all existing houses ?
clean_up = raw_input("Delete *ALL* old houses?  (y/n) [No]: ")
if clean_up == "y":
  for h in Marker.objects.filter(itemtype=housetype):
    h.delete()

for prop in dom.getElementsByTagName("item"):
  name = prop.getElementsByTagName("title")[0].firstChild.nodeValue.split(':')[0].strip()
  price = prop.getElementsByTagName("title")[0].firstChild.nodeValue.split('-')[1].strip()
  lon = prop.getElementsByTagName("geo:long")[0].firstChild.nodeValue
  lat = prop.getElementsByTagName("geo:lat")[0].firstChild.nodeValue
  link = prop.getElementsByTagName("link")[0].firstChild.nodeValue
  #thumbnail = prop.getElementsByTagName("media:content")[0].getAttribute('url')
  descr = prop.getElementsByTagName("description")[0].firstChild.nodeValue

  if verbose:
    print name
    print price
    print lon
    print lat
    print link
    #print thumbnail
    print descr
    print "---------------------------"

  house = Marker()
  house.name = name
  house.lat = lat
  house.lon = lon
  house.itemtype = housetype
  house.price = price
  house.link = link
  #house.thumbnail = thumbnail
  house.description = descr 
  house.save()
  
